import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hm_show_flutter/api/service/user_service.dart';
import 'package:hm_show_flutter/constant/string.dart';
import 'package:hm_show_flutter/constant/type.dart';
import 'package:hm_show_flutter/entity/user.dart';
import 'package:hm_show_flutter/entity/user_info_entity.dart';
import 'package:hm_show_flutter/entity/version_entity.dart';
import 'package:hm_show_flutter/event/user_update_event.dart';
import 'package:hm_show_flutter/style/style.dart';
import 'package:hm_show_flutter/utils/permission_util.dart';
import 'package:hm_show_flutter/utils/version_upgrade.dart';
import 'package:hm_show_flutter/utils/navigator_util.dart';
import 'package:hm_show_flutter/utils/shared_preferences_util.dart';
import 'package:hm_show_flutter/utils/toast_util.dart';
import 'package:hm_show_flutter/widgets/AppLoadingDialog.dart';
import 'package:hm_show_flutter/widgets/icon_text_arrow.dart';
import 'package:hm_show_flutter/widgets/support_view.dart';
import 'package:package_info/package_info.dart';
import 'package:r_upgrade/r_upgrade.dart';

class MineView extends StatefulWidget {
  @override
  _MineViewState createState() => _MineViewState();
}

class _MineViewState extends State<MineView> {
  UserService _userService = new UserService();
  UserModel _userModel;

  String _appName;
  String _versionName;
  int _versionCode;

  int id;

  @override
  void initState() {
    super.initState();
    _getUserInfo();
    _registerEventBus();
    _initVersion();
  }

  void _registerEventBus() {
    userUpdateEventBus.on<UserUpdateEvent>().listen((event) {
      _getUserInfo();
    });
  }

  void _getUserInfo() {
    _userService.getUserInfo((success) {
      UserInfoEntity model = success;
      _userModel = model.data.user;
      SharedPreferencesUtils.saveUser(_userModel);
      setState(() {});
    });
  }

  void _initVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    setState(() {
      _appName = packageInfo.appName;
      _versionName = packageInfo.version;
      _versionCode = int.parse(packageInfo.buildNumber);
    });
  }

  void _toLogin() {
    NavigatorUtils.goLogin(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        child: AppBar(
          automaticallyImplyLeading: false,
          centerTitle: true,
          elevation: 0,
          title: Text(
            "个人中心",
            style: TextStyle(color: Colors.white, fontSize: 18),
          ),
          backgroundColor: AppColors.mainColor,
          actions: <Widget>[
            GestureDetector(
              onTap: () {
                NavigatorUtils.goSettingPage(context);
              },
              child: Padding(
                padding: EdgeInsets.only(right: 10),
                child: Icon(
                  Icons.settings,
                  color: Colors.white,
                  size: 18,
                ),
              ),
            )
          ],
        ),
        preferredSize: Size.fromHeight(30),
      ),
      body: Container(
        color: Colors.grey[100],
        child: Column(
          children: <Widget>[
            Container(
              height: ScreenUtil.getInstance().setHeight(210.0),
              width: double.infinity,
              color: AppColors.mainColor,
              alignment: Alignment.center,
              child: _userModel != null
                  ? Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.only(
                              left: ScreenUtil.getInstance().setWidth(30.0)),
                          child: CircleAvatar(
                            radius: ScreenUtil.getInstance().setWidth(80),
                            backgroundImage: NetworkImage(
                              _userModel.url,
                            ),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(
                              left: ScreenUtil.getInstance().setWidth(10.0)),
                        ),
                        Padding(
                            padding: const EdgeInsets.only(
                                left: 12, top: 20, bottom: 20),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              children: <Widget>[
                                _userModel.name == null?Container():
                                Text(
                                  _userModel.name,
                                  style: TextStyle(
                                      fontSize:
                                          ScreenUtil.getInstance().setSp(26.0),
                                      color: Colors.white),
                                ),
                                _userModel.titleStr == null?Container():
                                Text(
                                  _userModel.titleStr,
                                  style: TextStyle(
                                      fontSize:
                                          ScreenUtil.getInstance().setSp(26.0),
                                      color: Colors.white),
                                ),
                                _userModel.companyName == null?Container():
                                Text(
                                  _userModel.companyName,
                                  style: TextStyle(
                                      fontSize:
                                          ScreenUtil.getInstance().setSp(26.0),
                                      color: Colors.white),
                                ),
                              ],
                            )),
                      ],
                    )
                  : InkWell(
                      onTap: () => _toLogin(),
                      child: Text(
                        Strings.CLICK_LOGIN,
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: ScreenUtil.getInstance().setSp(30.0)),
                      ),
                    ),
            ),
            Container(
              color: Colors.grey[100],
              padding: EdgeInsets.only(
                  top: ScreenUtil.getInstance().setHeight(20.0)),
            ),
            IconTextArrowView(
                Icons.assignment, Strings.APPOINTMENT, Colors.deepOrangeAccent, appointment),
            Container(
              height: ScreenUtil.getInstance().setHeight(1.0),
            ),
            IconTextArrowView(
                Icons.book, Strings.STUDY, Colors.deepPurpleAccent, study),
            Container(
              height: ScreenUtil.getInstance().setHeight(1.0),
            ),
            IconTextArrowView(
                Icons.star, Strings.COLLECTION, Colors.amber, collect),
            Container(
              height: ScreenUtil.getInstance().setHeight(1.0),
            ),
            IconTextArrowView(Icons.person, Strings.TEAM, Colors.green, member),
            Container(
              height: ScreenUtil.getInstance().setHeight(1.0),
            ),
            IconTextArrowView(
                Icons.filter_b_and_w, Strings.BRAND, Colors.red, brand),
            Container(
              height: ScreenUtil.getInstance().setHeight(1.0),
            ),
            IconTextArrowView(
              Icons.file_upload,
              Strings.UPDATE,
              Colors.blueAccent,
              update,
              rightText: _versionName == null ? " " : _versionName,
            ),
            Container(
              height: ScreenUtil.getInstance().setHeight(1.0),
            ),
            IconTextArrowView(
                Icons.person_pin, Strings.ABOUT_US, Colors.teal, aboutUs),
            Expanded(child: Container()),
            SupportView()
          ],
        ),
      ),
    );
  }

  void appointment() {
    if (_userModel != null) {
      NavigatorUtils.goAppointmentList(context);
    } else {
      _toLogin();
    }
  }

  void study() {
    if (_userModel != null) {
      NavigatorUtils.goCourseList(context);
    } else {
      _toLogin();
    }
  }

  void collect() {
    if (_userModel != null) {
      NavigatorUtils.goCollectionListPage(context);
    } else {
      _toLogin();
    }
  }

  void member() {
    if (_userModel != null) {
      NavigatorUtils.goMemberList(context);
    } else {
      _toLogin();
    }
  }

  void update() {
    if (_userModel != null) {
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return AppLoadingDialog();
          });

      _userService.getAppVersion((success) {
        VersionEntity entity = success;
        VersionData _versionInfo = entity.data;
        print("当前versionCode：" +
            _versionCode.toString() +
            " 最新versionCode：" +
            _versionInfo.versionCode.toString());
        if (_versionCode >= _versionInfo.versionCode) {
          Navigator.pop(context);
          ToastUtil.showToast("当前已是最新版本");
        } else {
          //
          Navigator.pop(context);
          if (Platform.isIOS) {
            ToastUtil.showToast("请前往App store更新应用");
            return;
          }
          showDialog<bool>(
              context: context,
              builder: (BuildContext context) {
                return WillPopScope(
                  onWillPop: () async => !_versionInfo.force,
                  child: _buildDialog(context, _versionInfo),
                );
              },
              barrierDismissible: false);
        }
      }, onFail: (fail) {
        Navigator.pop(context);
      });
    } else {
      _toLogin();
    }
  }

  Widget _buildDialog(
    BuildContext context,
    VersionData versionData,
  ) {
    List<Widget> _buttons = <Widget>[];

    if (versionData.force) {
      _buttons.add(_buttonUpdate(versionData.name, versionData.url));
    } else {
      _buttons.add(_buttonNext());
      _buttons.add(_buttonUpdate(versionData.name, versionData.url));
    }

    return CupertinoAlertDialog(
      title: Text('立即更新${versionData.name}?', style: TextStyle(fontSize: 14)),
      content: Column(
        children: <Widget>[
          Padding(padding: EdgeInsets.only(top: 10)),
          Text('检测到新版本 ${versionData.versionName}',
              style: TextStyle(fontSize: 12)),
          Padding(padding: EdgeInsets.only(top: 6)),
          Text(versionData.description, style: TextStyle(fontSize: 12)),
        ],
      ),
      actions: _buttons,
    );
  }

  Widget _buttonUpdate(String name, String url) {
    return CupertinoDialogAction(
      child: const Text('立即更新', style: TextStyle(fontSize: 13)),
      onPressed: () {
//        VersionUpgrade upgrade = new VersionUpgrade();
//        upgrade.executeDownload(name, url);
        Navigator.pop(context);
        PermissionUtil.checkStoragePermission().then((isGranted) {
          if (isGranted) {
            //有权限
            updateApp(name, url);
          }
        });
      },
    );
  }

  void updateApp(String name, String url) async {
    id = await RUpgrade.upgrade(url, apkName: name, isAutoRequestInstall: true);
  }

  Widget _buttonNext() {
    return CupertinoDialogAction(
      child: const Text('下次再说',
          style: TextStyle(fontSize: 13, color: Colors.grey)),
      onPressed: () {
        Navigator.pop(context, true);
      },
    );
  }

  void brand() {
    if (_userModel != null) {
      NavigatorUtils.goCompanyListPage(context, CompanyType.BRAND_LIST);
    } else {
      _toLogin();
    }
  }

  void aboutUs() {
    if (_userModel != null) {
      NavigatorUtils.goAboutUS(context);
    } else {
      _toLogin();
    }
  }
}
